package pkg;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import com.google.api.gbase.client.FeedURLFactory;
import com.google.api.gbase.client.GoogleBaseEntry;
import com.google.api.gbase.client.GoogleBaseFeed;
import com.google.api.gbase.client.GoogleBaseQuery;
import com.google.api.gbase.client.GoogleBaseService;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;


public class BaseEngine {

	private static String NAME = "example";

	private GoogleBaseService service;
	
	public BaseEngine(){
		service = new GoogleBaseService(NAME);
	}
	
	public boolean connect(String username, String password) {
		try {
			if (username.indexOf('@') < 1)
				username = username + "@gmail.com";
			service.setUserCredentials(username, password);

			return true;
		} catch (AuthenticationException e) {
			return false;
		}
	}

	public GoogleBaseFeed getQueryResult(GoogleBaseQuery query) {
		try {
			return service.query(query);
		} catch (IOException e) {
			return null;
		} catch (ServiceException e) {
			return null;
		}
	}

	public boolean insertGoogleBaseEntry(GoogleBaseEntry entry) {
		try {
			GoogleBaseEntry asInserted = service.insert(FeedURLFactory
					.getDefault().getItemsFeedURL(), entry);
			System.out.println(asInserted.getId());
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} catch (ServiceException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public GoogleBaseEntry getEntryFromID(String entryID){
		try {
			return service.getEntry(new URL(entryID));
		}
		catch (MalformedURLException e){
			return null;
		}
		catch (ServiceException e){
			return null;
		}
		catch (IOException e){
			return null;
		}
	}
}
